package cc.fozone.note.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.pegdown.Extensions;
import org.pegdown.PegDownProcessor;

import cc.fozone.note.service.ITemplateService;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class TemplateServiceImpl implements ITemplateService {
	private PegDownProcessor processor;
	private Configuration cfg;
	private String templateDir = "templates/default";
	private File templateDirFile;
	private TemplateExceptionHandler exceptionHandler;

	public TemplateServiceImpl() throws IOException {
		// TODO Auto-generated constructor stub
		processor = new PegDownProcessor(Extensions.ALL);
		cfg = new Configuration();

		templateDirFile = new File(templateDir);
		cfg.setDirectoryForTemplateLoading(templateDirFile);
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		
		exceptionHandler = new TemplateIngoreExceptionHandler();
		
		cfg.setTemplateExceptionHandler(exceptionHandler);
	}

	@Override
	public String convertToHTML(String title,String text) throws IOException, TemplateException {
		// TODO Auto-generated method stub
		String result = processor.markdownToHtml(text);
		Map<String, String> model = new HashMap<String, String>();
		model.put("path", templateDirFile.toURI().toString());
		model.put("placeholder", result);
		model.put("title",title);

		StringWriter writer = new StringWriter();
		Template template = cfg.getTemplate("index.html");
		template.process(model, writer);
		writer.flush();
		writer.close();

		return writer.getBuffer().toString();
	}
	@Override
	public String convertMarkdown(String markdown) {
		// TODO Auto-generated method stub
		if(StringUtils.isBlank(markdown)){
			return "";
		}
		return processor.markdownToHtml(markdown);
	}
}
